package cn.hj.basic.controller;

import cn.hj.basic.util.AjaxResult;
import cn.hj.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传接口
     * @return
     */
    @PostMapping
    public AjaxResult upLoad(@RequestPart(required = true,value = "file")MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String uploadPath = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.newAjaxResult().setResultObj(uploadPath);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.newAjaxResult().setSuccess(false).setMessage("上传失败!!!");
        }
    }

    //删除接口
    @DeleteMapping  // ?path=/group1/M00/02/22/rBE3kWHNVcKAf1QKAAF-6xZ0lWg132.jpg
    public AjaxResult delete(@RequestParam String path){
        try {
            String pathTmp = path.substring(1); // group1/M00/02/22/rBE3kWHNVcKAf1QKAAF-6xZ0lWg132.jpg
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String fileName = pathTmp.substring(pathTmp.indexOf("/")+1);// M00/02/22/rBE3kWHNVcKAf1QKAAF-6xZ0lWg132.jpg
            FastDfsUtil.delete(groupName, fileName);

            return AjaxResult.newAjaxResult();//把上传之后的相对路径设置给resultObj属性
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.newAjaxResult().setSuccess(false).setMessage("删除失败!!!");
        }
    }
}
